package com.wyp168.socket.tcp.upload02;

import com.wyp168.socket.utils.StreamUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @ClassName Sever
 * @Title TODO
 * @Description TODO
 * @Author wyp168
 * @Date 2022/10/29 12:02
 */
public class Server {
    public static void main(String[] args) throws Exception {
        //服务端监听18082端口，等待客户端发送下载文件请求
        ServerSocket serverSocket = new ServerSocket(18082);

        Socket socket = serverSocket.accept();
        InputStream inputStream = socket.getInputStream();
        byte[] buf = new byte[1024];
        int readLen;
        String fileName = "";
        while ((readLen = inputStream.read(buf)) != -1) {
            fileName = new String(buf, 0, readLen);
        }

        if (!fileName.equals("wyp168.jpg")) {
            fileName = "WYP1115.jpg";
        }

        OutputStream outputStream = socket.getOutputStream();
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("/Users/wangyuanpeng/com/" + fileName));
        byte[] fileBytes = StreamUtils.streamToByteArray(bis);
        outputStream.write(fileBytes);
        socket.shutdownOutput();

        //关闭资源
        outputStream.close();
        bis.close();
        inputStream.close();
        socket.close();
        serverSocket.close();

        System.out.println("服务端退出");

    }
}
